<?php
/**
 * 邮寄管理 
 * 
 */
namespace Admin\Controller;
use Think\Controller;
use Common\Controller\BaseController;
use Common\ORG\Page,Common\ORG\AttUpload,Common\ORG\Excel;

class DeliveryController extends BaseController {
	//首页
	public function index(){
		$arr = D("Delivery")->index($_GET,$this->m_psize);
		e_json($arr);
	}
	//添加邮寄信息
	public function deliveryAdd(){
		$list = D("Delivery")->deliveryAdd($_POST);
		e_json($list);
	}
	//编辑邮寄信息
	public function deliveryEeditor(){
		$res = D("Delivery")->deliveryEeditor($_POST);
		e_json($res);
	}
	//合同邮寄信息编辑
	public function contractEditor(){
		$res = D("Delivery")->ContractEditor($_POST);
		e_json($res);
	}
	//合同邮寄批量操加载
	public function batch(){
		$res      = array('rcode'=>1,'contract'=>NULL, 'msg'=> 'OK');
		$where['contract.sign_status'] = 0;
		$where['contract.state'] = 0;     
		$contract = M("contract")
				->field("contract.contract_id,contract.sales_person,contract.sales_sector,contract.sales_manager,contract.sales_sub_company,customer.customer_id,customer.nickname as customer_nickname,customer.phone as customer_phone,customer.address as customer_address,delivery.delivery_id,delivery.recipients,delivery.phone,delivery.address,delivery.delivery_num,delivery.send_way,delivery.send_time,delivery.remark,delivery.status")
				->join("LEFT JOIN customer ON contract.customer_id  = customer.customer_id")
				->join("LEFT JOIN delivery ON contract.contract_id  = delivery.source_id")
				->join("LEFT JOIN product  ON contract.product_id   = product.product_id")
				->join("LEFT JOIN user     ON contract.sales_person = user.user_id")
				->where($where)
				->order("contract.contract_id desc")
				->select();
		$time = date("Y-m-d");
		foreach ($contract as &$value) {
			//经理
			$wheres_r['user_id']     = $value['sales_manager'];
        	$manager = M('user')->field("user_id,nickname as manager_name")->where($wheres_r)->find();
        	$value['manager']        = $manager['manager_name'];
        	$value['manager_id']     = $manager['user_id'];
        	//业务员
        	$salesman['user_id']     = $value['sales_person'];
        	$user = M('user')->field("user_id,nickname")->where($salesman)->find();
        	$value['user_name']      = $user['nickname'];
        	$value['user_id']        = $user['user_id'];
        	if(strtotime($value['send_time'] ) > 0) $value['send_time'] = date("Y-m-d",strtotime($value['send_time']));
        	else $value['send_time'] = $time;
        	//默认值
        	if(empty($value['recipients'])) $value['recipients'] = $value['customer_nickname'];
        	if(empty($value['phone']))      $value['phone']      = $value['customer_phone'];
        	if(empty($value['address']))    $value['address']    = $value['customer_address']; 
		}
        if( $contract ){
			$res['rcode']    = 1;
			$res['contract'] = $contract;
		}else{
			$res['msg'] = "退款记录暂时没有数据";
		}
		e_json( $res );	          
	}
	
	//确认信息批量编辑加载
	public function confirm_show(){
		$status = I("get.status");
		$matter_state = I("get.matter_state");
		if(!empty($matter_state) && !empty($status) ){
			$where['delivery.source_type'] = $status;
			$where['delivery.status']      = 0;
			$list = M("delivery")
					->field("customer.customer_id,customer.nickname as customer_name,delivery.*,user.nickname as user_name,sector.sector_name,contract.mount as contract_mount,contract.start_time,contract.state,contract.sign_status,contract.contract_id,contract.end_time,product.name")
					->join("LEFT JOIN customer ON delivery.customer_id = customer.customer_id")
					->join("LEFT JOIN contract ON delivery.source_id   = contract.contract_id")
					->join("LEFT JOIN product  ON contract.product_id  = product.product_id")
					->join("LEFT JOIN user     ON delivery.sales_id    = user.user_id ")
					->join("LEFT JOIN sector   ON delivery.sales_subcompany = sector.sector_id")
                    ->where($where)
                    ->order(" delivery.delivery_id desc ")
		            ->select();

			//客户信息、截取时间为 Y-m-d
			foreach ($list as &$value) { 
				$value['send_time']  = date('Y-m-d',strtotime($value['send_time'])); 
				$value['start_time'] = date('Y-m-d',strtotime($value['start_time']));
				$value['end_time']   = date('Y-m-d',strtotime($value['end_time']));
				$value['contract_mount'] = floor($value['contract_mount']);
				//所属经理
				$manager_r['user_id'] = $value['sales_manager'];
				$manager = M("user")->field("nickname as manager_name")->where($manager_r)->find();
				$value['manager']   = $manager['manager_name'];
			}
		}
		if($list){
			$res['confirm'] = $list;
			$res['record']  = 1;
		}else{
			$res['msg']     = "你查找的信息不存在!!!";
		}
		e_json($res);
	}
	//确认信息编辑
	public function confirm_editor(){
		if($_POST['batch']){
			foreach ($_POST['batch'] as $key => $value) {
				$map['status'] = 20;
				$where['delivery_id'] = $value;
				$delivery = M("delivery")->where($where)->save($map);
				if(!$delivery) $failure[] = $value;
			}
			if($failure){
				$res['failure']  =  explode(',',$failure); 
				$res['rcode'] = 2;
			}  
			//数据统计
			$res['sum'] = count($_POST['batch']);//数据总数 
			$res['failures'] = count($failure);//失败数据
			$res['successful'] = count($_POST['batch'])-count($failure);//成功数据
		}else{
			$map['status'] = 20;
			$where['delivery_id'] = I("post.delivery_id");
			$delivery = M("delivery")->where($where)->save($map);
			if($delivery) $res['rcode'] = 1;
		}
		e_json($res);
	}
	//取消邮寄记录
	public function cancel(){
		$where['delivery_id'] = I("delivery_id");
		$map['status'] = 50;
		$delivery = M("delivery")->where($where)->save($map);
		if($delivery) $res['rcode'] = 1;
		else $res['rcode'] = 2;
		e_json($res);
	}
	//导出邮寄
	public function export_delivery(){
		//搜索信息检索 
		$customer = I("customer");
		if(!empty($customer)){
			$customer_ = $arr['customer'];
			$maps['customer.nickname'] = array('like','%'.$customer.'%');
			$maps['customer.phone']    = array('like','%'.$customer.'%');
			$maps['customer.customer_code'] = array('like','%'.$customer.'%');
			$maps['_logic']   = 'OR';
			$wheres['_complex'] = $maps;
		}
		$sales = I("sales");
		if(!empty($sales)){
			$wheres['user.nickname'] = array('like','%'.$sales.'%');
		}
		$order_num = I("order_num");
		if(!empty($order_num)){
			$wheres['delivery.order_num']    = array('like','%'.$order_num.'%');
		}

		//区间与时间检索
		$stime    = I('get.first_time','','trim');
		$etime    = I('get.second_time','','trim');
		if( $stime && $etime ){
			$stime = date('Y-m-d 00:00:00',strtotime($stime));
			$etime = date('Y-m-d 23:59:59', strtotime($etime));
			if(strtotime($stime) < strtotime($etime)) $wheres['delivery.create_time'] = array('between',array($stime,$etime));
			else $wheres['delivery.create_time'] = array('between',array($etime,$stime));
		}elseif($stime  && !$etime ){
			$stime = date('Y-m-d 00:00:00',strtotime($stime));
			$wheres['delivery.create_time'] =  array('egt',$stime);
		}elseif(!$stime && $etime ){
			$etime = date('Y-m-d 23:59:59', strtotime($etime));
			$wheres['delivery.create_time'] = array('elt', $etime);
		}
		$wheres['delivery.source_type']  = I('matter');
		$wheres['delivery.is_export'] = array(array('EXP','IS NULL'),array('neq',10),'or');
		$wheres['delivery.status'] = 20;
		/**********************************************************************/
		$Delivery     = M("delivery");

		if(isset($_GET['default'])){
		    $list = "";
		}else{
		    $list = $Delivery
				->field("contract.contract_id,contract.mount,contract.sign_status,contract.end_time,contract.start_time,contract.state,contract.order_num,customer.nickname as customer_name,customer.phone,product.name,delivery.address,delivery.sales_id,delivery.sales_manager,delivery.	sales_subcompany,delivery.remark,delivery.delivery_num,delivery.delivery_id,delivery.recipients,delivery.phone as delivery_phone")
                ->join(" LEFT JOIN contract ON delivery.source_id   = contract.contract_id ")
                ->join(" LEFT JOIN customer ON delivery.customer_id = customer.customer_id ")
                ->join(" LEFT JOIN product  ON contract.product_id  = product.product_id ")
                ->join(" LEFT JOIN user     ON contract.sales_person  = user.user_id ")
                ->where($wheres)
                ->order("delivery.delivery_id desc")
	            ->select();
	    }
		//客户信息、截取时间为 Y-m-d
		import("Common.ORG.Excel");
		$SExcel = new \Common\ORG\Excel();
		$SSheet = new \Common\ORG\Sheet("合同记录");
		$matter = I("matter");
	
		if($matter == 2 || $matter == 3){
			//发票记录、退款协议 
			$headline = array('订单号','客户名','金额','收件人','收件人电话','收件人地址','快递运单号');
		}else{
			//合同邮寄记录
			$headline = array('订购金额','快递订单号','客户姓名','电话','产品类型','服务期限','合同开始时间','合同是否签好','合同时长','合同编号','邮寄地址','业务员','经理','团队','快递运单号','备注');
		}
		$SSheet->setColumn( $headline );
		//获取当前时间
		$export_time = substr(date("Y"),2,4).date(date("md"));
		foreach ($list as $key => $value) {
			$arr   = array();
			//业务员
			$sale['user_id']   = $value['sales_id'];
			$user = M("user")->field("nickname")->where($sale)->find();
			//经理
			$sector['user_id'] = $value['sales_manager'];
			$manager = M("user")->field("nickname")->where($sector)->find();
			//团队
			$team['sector_id'] = $value['sales_subcompany'];
			$company = M("sector")->field("sector_name")->where($team)->find();
			if(strlen($value['sales_subcompany']) == 1 )     $value['sales_subcompany'] = '0'.$value['sales_subcompany']; 
			elseif(strlen($value['sales_subcompany']) > 2 )  $value['sales_subcompany'] = substr($value['sales_subcompany'],2);

			//邮寄订单号	
			if(strlen($value['delivery_id']) == 1 ){
				$value['delivery_order_num'] = $export_time.$value['sales_subcompany'].'00'.$value['delivery_id'];
			}elseif(strlen($value['sales_subcompany']) > 3 ){
				$value['delivery_order_num'] = $export_time.$value['sales_subcompany'].substr($value['delivery_id'],-3);
			}else{
				$value['delivery_order_num'] = $export_time.$value['sales_subcompany'].$value['delivery_id'];
			}  

			//合同时长计算
			$length['contract_id'] = $value['source_id'];
			$length['source_type'] = 1;
			$delivery = M("delivery")->field("status,send_time")->order("delivery_id desc")->find();
			if($delivery['status'] == 40){
				$results = ceil((strtotime($delivery['send_time'])-strtotime($value['start_time']))/(3600*24));
			}elseif($delivery['status'] < 40 ){
				$results = ceil((strtotime(date("Y-m-d H:i:s"))-strtotime($value['start_time']))/(3600*24));
			}else{
				$results = '';
			}
					
			//写入excel
			if($matter == 1){
				$arr[] = floor($value['mount']);
				$arr[] = ' '.$value['delivery_order_num'];
				$arr[] = $value['customer_name'];
				$arr[] = ' '.$value['phone'];
				$arr[] = $value['name'];
				$arr[] = $value['end_time'];
				$arr[] = $value['start_time'];
				$arr[] = $value['state'] == 1?'已签好':($value['state'] == 3?'已签好':'未签好');
				$arr[] = $results;//时长统计
				$arr[] = $value['order_num'];
				$arr[] = $value['address'];
				$arr[] = $user['nickname'];
				$arr[] = $manager['nickname'];
				$arr[] = $company['sector_name'];
				$arr[] = $value['delivery_num'];
				$arr[] = $value['remark'];
			}else{	
				//发票、退款金额
				if($matter == 2){
					$invoice['delivery_id'] = $value['delivery_id'];
					$money = M("invoice")->field("money as sum_money")->where($invoice)->find();
				}else{
					$refund['contract_id'] = $value['contract_id'];
					$money = M("refund")->field(" sum(pay_mount) as sum_money")->where($refund)->find();
				}
				
				$arr[] = ' '.$value['delivery_order_num'];
				$arr[] = $value['customer_name'];
				$arr[] = $money['sum_money'];
				$arr[] = $value['recipients'];
				$arr[] = ' '.$value['delivery_phone'];
				$arr[] = $value['address'];
				$arr[] = $value['delivery_num'];
			}
			$saveOrder['delivery_id'] = $value['delivery_id'];
			$order['order_num'] = $value['delivery_order_num'];
			$order['is_export'] = 10;
			$order['status']    = 30;
			$order['send_time'] = date("Y-m-d H:i:s");
			M("delivery")->where($saveOrder)->save($order);
			
			//更改合同状态
			$save_where['contract_id'] = $value['contract_id'];
			$see_contract = M("contract")->field("state")->where($save_where)->find();
			if($see_contract['state']!=1 && $see_contract['state']!=3){
				
				$save_state['state'] = 4;
				M("contract")->where($save_where)->save($save_state);
			}
			$SSheet->addRow( $arr );
		}
	
		$exportData = $SExcel->add_sheet( $SSheet)->export_sheet("数据导出");

		if( $exportData['rcode'] ){
			$exportData['name'] = basename( $exportData['data']['view_path'] );
			$exportData['excel'] = file_get_contents( $exportData['data']['real_path'] );
			echo $exportData['excel'];
			exit();
		}
	}
	//导入邮寄
	public function import_delivery(){
		$type = I('get.type','0','intval');
		if( IS_POST ){
	      $fname  = I('post.name','file', 'trim');
	      $newDir = I('post.newname','','trim');
	      $Mdo    = new AttUpload();
	      $MExcel = new Excel();
	      $realpath = '';
	      //Excel文件上传
	      $ret = $Mdo->http_upload( $fname, $newDir);
	      if ($ret && (1 != $ret['rcode'])) {
	        $res['msg']   = $ret['msg'];
	      }else{
	        $realpath = $ret['data']['view_path'];
	      } 
	      //Excel 解析
	      $excelData = $MExcel->parse_file(  $realpath );
	      foreach ($excelData['data']['row']['s0'] as $key => $value) {
	      	if($type == 1){
	      		$where['order_num']   = $value[1];
	      		$map['delivery_num']  = $value[14];
	      		$map['status']        = 40; 
	      		$check = M("delivery")->field("delivery_num")->where($where)->find();
	      		if($check['delivery_num'] != $value[14] && $value[14]!=""  ){
		      		$save = M("delivery")->where($where)->save($map);
		      		if(!$save){
		      			$failure[] = $value[9];
		      		}else{
		      			//更新合同状态
			      		$wheres['order_num'] = $value[9];
			      		$contract = M("contract")->field("state,sign_status,type")->where($wheres)->find();
			      		if($contract['state'] != 1 && $contract['state'] !=3 && $contract['sign_status'] == 10){
			      			if($contract['type']!=1) $maps['type'] = 1;
			      			$maps['state'] = 1;
			      			M("contract")->where($wheres)->save($maps);
			      		}
		      		}
		      	}else{
		      		$repeat[] = $value;
		      	}
	      	}else{
	      		$where['order_num']   = $value[0];
	      		$map['delivery_num']  = $value[6];
	      		$map['status']        = 40;
	      		$check = M("delivery")->field("delivery_num")->where($where)->find();
      			if($check['delivery_num'] != $value[6]  ){
		      		$save = M("delivery")->where($where)->save($map);
		      		if(!$save) $failure[] = $value[9];
		      	}else{
		      		$repeat[] = $value;
		      	}
	      	}
	      }
	      if($failure){
	      	$res['failure'] = implode('、',$failure);
	      }
	      //数据统计
	      $res['statistics']['sum'] = count($excelData['data']['row']['s0']);//上传总数
	      $res['statistics']['failures'] = count($failure); //修改失败数据
	      $res['statistics']['repeat']   = count($repeat);  //重复数据
	      $res['statistics']['successful']  = count($excelData['data']['row']['s0'])-count($failure)-count($repeat);  //成功数据
	      e_json($res);
	    }
	}
	//邮寄完成操作
	public function complete(){
		$state = I("state");
		$sign_status = I("sign_status");
		
		//是否更新合同状态
		$where['contract_id'] = I("contract_id"); 
		if($state==0){
			$map['state'] = 4;
		}elseif($state==4 && $sign_status==10){
			$map['state'] = 1;
			$map['type']  = 1;
		}
		$contract = M("contract")->where($where)->save($map);
		
		//是否变更邮寄状态
		$wheres['delivery_id'] = I("delivery_id");		
		$maps['status'] = 40;
		$maps['create_time']   = date("Y-m-d H-i-s");
		$maps['delivery_num']  = I("delivery_num");
		$delivery = M("delivery")->where($wheres)->save($maps);
		if($delivery){
			$res['rcode'] = 1;
		} else{
			$res['msg'] = "编辑完成邮寄失败!!!!";
		}
		e_json($res);
	}
	//运单号是否重复检测
	public function repeatCheck(){
		$where['delivery_num'] = I("delivery_num");
		$delivery = M("delivery")->where($where)->find();
		if($delivery) $res['checkResults'] = 1;
		else $res['checkResults'] = 2;
		e_json($res);
	}
	//删除邮寄记录
	public function Delete(){
		$Delivery = M("delivery");
		$where['delivery_id'] = I("post.delivery_id");
		$results  = $Delivery->where($where)->delete();
		if($results)
			$res['rcode'] = 1;
		else
			$res['msg']   = "删除失败!";
		e_json($res);
	}
	//公用参数
	public function communal(){
		$res['today'] = date("Y-m-d");
		e_json($res);
	}
}